/**
 * 楼盘相册
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    var tmpl = require("tmpl");
    var dialog = require("dialog");
    var buidingSetting = require("./building_setting");
    require("pagination");
    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/building-info/"; //api前缀

    var BuildingPhoto = {
        photoList:[], //相册列表
        photoTotal:0, //总记录数
        appPhotoList:[], //应用的相册列表
        appPhotoIds:[], //已选择的相册id列表
        pageIndex:1,
        pageSize:10,
        init: function(){
            this.appPhotoIds = [];
            this.bindEvent();
            if(buidingSetting.proj_id){
                this.getAppPhotoList();
            }
        },
        //建筑类型
        bindEvent: function() {
            var _this = this;
            $("#btn_save").off().on("click", function(e) {
                e.preventDefault();
                _this.saveOrders();
            });
            var $photo_list = $("#app_photo_list");
            $photo_list.off();
            $photo_list.on("click",".js-sel-photo",function(e){
                e.preventDefault();
                _this.showPopPhotoList();
            });
            $photo_list.on("click",".js-del",function(e){
                e.preventDefault();
                var oid = $(e.currentTarget).closest("li").attr("id");
                if(oid){
                    _this.delPhoto(oid);
                }
            });
        },
        //应用已选择的相册列表
        getAppPhotoList:function(){
            var url = api_prefix + "get-app-photo-list";
            var data = {
                app:"5003",
                proj_id:buidingSetting.proj_id
            };
            util.myAjax({
                url: url,
                type: "get",
                context: this,
                data:data,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.appPhotoList = json.data.list || [];
                        this.initAppPhotoList(this.appPhotoList);
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    ui.removeLoading();
                }
            });
            ui.loading();
        },
        initAppPhotoList:function(list){
            if(list.length == 0){
                $("#btn_save").hide();
            }else{
                $("#btn_save").show();
            }
            var html = tmpl("photo_list_tmpl",{list:list});
            $("#app_photo_list").html(html);
            
            //初始化排序控件
            $("#app_photo_list .js-order").each(function(){
                ui.initCount($(this).attr("id"));
            });
        },
        initPager:function(total){
            var _this = this;
            $('#pager').pagination(total,{
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                callback: function (pageIndex, jq) {
                    if(pageIndex !== _this.pageIndex){
                        //切换分页时，将选中的相册id保存下来
                        _this.saveSelPhotoIds();
                        _this.pageIndex = pageIndex;
                        _this.getPhotoList(pageIndex);
                    }
                },
                items_per_page: this.pageSize //每页显示1项
            });
            this.pagerInited = true;
        },
        //切换分页时，将选中的相册id保存下来
        saveSelPhotoIds:function(){
            var $cbList = $("#album_list :checkbox");
            var photoIds = this.appPhotoIds;
            $cbList.each(function(){
                var id = $(this).val();
                var index = $.inArray(id,photoIds);
                if(index == -1){
                    if($(this).prop("checked")){
                        photoIds.push(id);
                    }
                }else if($(this).prop("checked") == false){
                    photoIds.splice(index,1); //从数组中删除
                }
            });
            this.appPhotoIds = photoIds;
        },
        //删除应用选择的相册
        delPhoto:function(oid){
            var _this = this;
            util.confirm("您确定要删除吗？", {
                ok: function() {
                    var url = api_prefix + "del-app-selected-photo";
                    var data = {
                      po_photo_appsId:oid  
                    };
                    util.myAjax({
                        url: url,
                        type: "POST",
                        data: data,
                        success: function(json) {
                            if (json.retCode == 0) {
                                _this.getAppPhotoList();
                            } else {
                                ui.showErrTip(json.errMsg);
                            }
                        }
                    });
                }
            });
        },
        //保存应用选择的相册
        saveSelectedPhotos:function(photoIds){
            var url = api_prefix + "save-app-selected-photo";
            var data = {
                app:"5003",
                proj_id:buidingSetting.proj_id,
                photoIdsArr:JSON.stringify(photoIds)  
            };
            util.myAjax({
                url: url,
                type: "POST",
                data:data,
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.getAppPhotoList();
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                }
            });
        },
        //相册列表
        getPhotoList:function(pageIndex){
            if(typeof pageIndex === "undefined"){
                pageIndex = 1;
            }
            var url = api_prefix + "get-photo-list";
            var data = {
                pageIndex:pageIndex,
                pageSize:this.pageSize,
                app:"5003",
                proj_id:buidingSetting.proj_id
            };
            util.myAjax({
                url: url,
                type: "get",
                data:data,
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.photoList = json.data.list || [];
                        this.photoTotal = parseInt(json.data.total,10);
                        
                        var html = tmpl("sel_photo_tmpl",{list:this.photoList});
                        $("#album_list").html(html);
                        this.initCheckBox();
                        if(!this.pagerInited){
                            this.initPager(this.photoTotal);
                        }
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    ui.removeLoading();
                }
            });
            ui.loading("album_list");
        },
        showPopPhotoList:function(){
            this.pageIndex = 1;
            var _this = this;
            var d = dialog({
                title: "选择相册",
                content: $("#sel_photo_div").html(),
                width:850,
                height:400,
                onshow: function(){
                    _this.appPhotoIds = [];
                    _this.pagerInited = false;
                    _this.getPhotoList();
                },
                onclose:function(){
                    this.remove();
                },
                ok: function() {
                    var $cbList = $("#album_list :checkbox:checked");
                    var photoIds = _this.appPhotoIds;
                    $cbList.each(function(i){
                        var id = $(this).val();
                        if($.inArray(id,photoIds) == -1){
                            photoIds.push(id);
                        }
                    });
                    if(photoIds.length > 0){
                        _this.saveSelectedPhotos(photoIds);
                    }
                    return true;
                },
                cancel: function() {
                }
            });
            d.showModal();
        },
        setCbAll:function(){
            var $temp = $("#album_list :checkbox");
            if($temp.length == $temp.filter(":checked").length){
                $("#cbAll").prop("checked",true);
            }else{
                $("#cbAll").prop("checked",false);
            }
        },
        initCheckBox:function(){
            var _this = this;
            // 全选
            $("#cbAll").off().on("click",function(){
                $("#album_list :checkbox").prop("checked",this.checked);
            });
            var $cbList = $("#album_list :checkbox");
            $cbList.off().on("click",function(e){
                _this.setCbAll();
            });
            $("#album_list .album-border").click(function(e){
                var $cb = $(this).find(":checkbox");
                $cb.prop("checked",!$cb.prop("checked"));
                _this.setCbAll();
            });
            //设置选中状态
            var photoIds = this.appPhotoIds;
            $cbList.each(function(){
                if($.inArray($(this).val(),photoIds) != -1){
                    $(this).prop("checked",true);
                }
            });
            if($cbList.length > 0 && $cbList.length == $cbList.filter(":checked").length){
                $("#cbAll").prop("checked",true);
            }else{
                $("#cbAll").prop("checked",false);
            }
            $cbList = null;
        },
        //保存应用下选择的相册的显示顺序
        saveOrders:function(){
            var $photoList = $("#app_photo_list li.js-photo-item");
            if($photoList.length == 0){
                return false;
            }
            var arr = [];
            $photoList.each(function(){
                var $el = $(this);
                var order = parseInt($el.find("input").val(),10) || 0;
                arr.push({
                    po_photo_appsId:$el.attr("id"),
                    orders:order
                });
            });
            var data = {
                batch:JSON.stringify(arr)
            };
            var url = api_prefix + "save-app-selected-orders";
            util.myAjax({
                url: url,
                type: "POST",
                context: this,
                data: data,
                success: function(json) {
                    if (json.retCode == 0) {
                        ui.showSucTip();
                        this.getAppPhotoList();
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                }
            });
        }
    };
    module.exports = BuildingPhoto;
});